{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Copyright 2014 Brett Slatkin, Pearson Education Inc.\n",
    "#\n",
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "#     http://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License.\n",
    "\n",
    "# Preamble to mimick book environment\n",
    "import logging\n",
    "from pprint import pprint\n",
    "from sys import stdout as STDOUT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 1\n",
    "def normalize(numbers):\n",
    "    total = sum(numbers)\n",
    "    result = []\n",
    "    for value in numbers:\n",
    "        percent = 100 * value / total\n",
    "        result.append(percent)\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[11.538461538461538, 26.923076923076923, 61.53846153846154]\n"
     ]
    }
   ],
   "source": [
    "# Example 2\n",
    "visits = [15, 35, 80]\n",
    "percentages = normalize(visits)\n",
    "print(percentages)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### StopIteration exception gieves you no result!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 3\n",
    "path = 'my_numbers.txt'\n",
    "with open(path, 'w') as f:\n",
    "    for i in (15, 35, 80):\n",
    "        f.write('%d\\n' % i)\n",
    "\n",
    "def read_visits(data_path):\n",
    "    with open(data_path) as f:\n",
    "        for line in f:\n",
    "            yield int(line)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[]\n"
     ]
    }
   ],
   "source": [
    "# Example 4\n",
    "it = read_visits('my_numbers.txt')\n",
    "percentages = normalize(it)\n",
    "print(percentages)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[15, 35, 80]\n",
      "[]\n"
     ]
    }
   ],
   "source": [
    "# Example 5\n",
    "it = read_visits('my_numbers.txt')\n",
    "print(list(it))\n",
    "print(list(it))  # Already exhausted"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### copy the iterator? It could be large!! BAD."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 6\n",
    "def normalize_copy(numbers):\n",
    "    numbers = list(numbers)  # Copy the iterator\n",
    "    total = sum(numbers)\n",
    "    result = []\n",
    "    for value in numbers:\n",
    "        percent = 100 * value / total\n",
    "        result.append(percent)\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[11.538461538461538, 26.923076923076923, 61.53846153846154]\n"
     ]
    }
   ],
   "source": [
    "# Example 7\n",
    "it = read_visits('my_numbers.txt')\n",
    "percentages = normalize_copy(it)\n",
    "print(percentages)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### returns\ta\tnew\titerator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 8\n",
    "def normalize_func(get_iter):\n",
    "    total = sum(get_iter())   # New iterator\n",
    "    result = []\n",
    "    for value in get_iter():  # New iterator\n",
    "        percent = 100 * value / total\n",
    "        result.append(percent)\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[11.538461538461538, 26.923076923076923, 61.53846153846154]\n"
     ]
    }
   ],
   "source": [
    "# Example 9\n",
    "percentages = normalize_func(lambda: read_visits(path))\n",
    "print(percentages)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### __iter___"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 10\n",
    "class ReadVisits(object):\n",
    "    def __init__(self, data_path):\n",
    "        self.data_path = data_path\n",
    "\n",
    "    def __iter__(self):\n",
    "        with open(self.data_path) as f:\n",
    "            for line in f:\n",
    "                yield int(line)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[11.538461538461538, 26.923076923076923, 61.53846153846154]\n"
     ]
    }
   ],
   "source": [
    "# Example 11\n",
    "visits = ReadVisits(path)\n",
    "percentages = normalize(visits)\n",
    "print(percentages)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 12\n",
    "def normalize_defensive(numbers):\n",
    "    if iter(numbers) is iter(numbers):  # An iterator -- bad!\n",
    "        raise TypeError('Must supply a container')\n",
    "    total = sum(numbers)\n",
    "    result = []\n",
    "    for value in numbers:\n",
    "        percent = 100 * value / total\n",
    "        result.append(percent)\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[11.538461538461538, 26.923076923076923, 61.53846153846154]"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Example 13\n",
    "visits = [15, 35, 80]\n",
    "normalize_defensive(visits)  # No error\n",
    "visits = ReadVisits(path)\n",
    "normalize_defensive(visits)  # No error"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Example 14\n",
    "try:\n",
    "    it = iter(visits)\n",
    "    normalize_defensive(it)\n",
    "except:\n",
    "    logging.exception('Expected')\n",
    "else:\n",
    "    assert False"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
